package org.example.backend.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;

@RestController
@RequestMapping("/api/test")
public class TestController {

    // 使用自定义 Cookie 名称避免冲突
    private static final String CUSTOM_SESSION_COOKIE = "CUSTOM_SESSION";

    @GetMapping("/readCookie")
    public String readCookie(
            @CookieValue(value = CUSTOM_SESSION_COOKIE, defaultValue = "default") String sessionId) {
        return "Session ID: " + sessionId;
    }

    @GetMapping("/setCookie")
    public ResponseEntity<String> setCookie(@RequestParam(defaultValue = "newSessionValue") String value) {
        ResponseCookie cookie = ResponseCookie.from(CUSTOM_SESSION_COOKIE, value)
                .httpOnly(true)
                .secure(true)  // 确保生产环境使用 HTTPS
                .path("/")
//                .maxAge(Duration.ofSeconds(10))
                .maxAge(Duration.ofHours(1))
                .sameSite("Lax")  // 显式设置 SameSite
                .build();

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, cookie.toString())
                .body("Cookie has been set");
    }

    @GetMapping("/deleteCookie")
    public ResponseEntity<String> deleteCookie() {
        // 通过设置 maxAge=0 立即删除 Cookie
        ResponseCookie cookie = ResponseCookie.from(CUSTOM_SESSION_COOKIE, "")
                .httpOnly(true)
                .secure(true)
                .path("/")
                .maxAge(Duration.ZERO)
                .sameSite("Lax")
                .build();

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, cookie.toString())
                .body("Cookie has been deleted");
    }
}